<?php
namespace app\admin\model;

use think\Model;
use think\Db;
use app\admin\model\DepartmentModel;

class RoleModel extends Model
{
    // 确定链接表名
    protected $name = 'role';

    /**
     * 根据搜索条件获取角色列表信息
     * @param $where
     * @param $offset
     * @param $limit
     */
    public function getRoleByWhere($where, $offset, $limit)
    {
		$DepartModel = new DepartmentModel();
		$departs = $DepartModel->getCanSeeDepart(session('id'));
		foreach($departs as &$d){
			$d = $d['id'];
		}
        return $this->where("department_id",'in',$departs)
			->where($where)->limit($offset, $limit)->order('id desc')->select();
    }

    /**
     * 根据搜索条件获取所有的角色数量
     * @param $where
     */
    public function getAllRole($where)
    {
		$DepartModel = new DepartmentModel();
		$departs = $DepartModel->getCanSeeDepart(session('id'));
		foreach($departs as &$d){
			$d = $d['id'];
		}
        return $this->where("department_id",'in',$departs)->where($where)->count();
    }

    /**
     * 插入角色信息
     * @param $param
     */
    public function insertRole($param)
    {
        try{

            $result =  $this->validate('RoleValidate')->save($param);
            if(false === $result){
                // 验证失败 输出错误信息
                return msg(-1, '', $this->getError());
            }else{

                return msg(1, url('role/index'), '添加角色成功');
            }
        }catch(PDOException $e){

            return msg(-2, '', $e->getMessage());
        }
    }

    /**
     * 编辑角色信息
     * @param $param
     */
    public function editRole($param)
    {
        try{

            $result = $this->validate('RoleValidate')->save($param, ['id' => $param['id']]);

            if(false === $result){
                // 验证失败 输出错误信息
                return msg(-1, '', $this->getError());
            }else{

                return msg(1, url('role/index'), '编辑角色成功');
            }
        }catch(PDOException $e){
            return msg(-2, '', $e->getMessage());
        }
    }

    /**
     * 根据角色id获取角色信息
     * @param $id
     */
    public function getOneRole($id)
    {
        $info = $this->where('id', $id)->find();
        $info['department_name'] = Db::name('department')->where('id',$info['department_id'])->value('name');
        return $info;
    }

    /**
     * 删除角色
     * @param $id
     */
    public function delRole($id)
    {
        try{
            $this->where('id', $id)->delete();
			$user = Db::name("user")->where("role_id",$id)->field("id")->select();
			foreach($user as $v){
				DB::name('user')->where('id',$v['id'])->delete();
				DB::name('users_company')->where('uid',$v['id'])->delete();
				DB::name('users_government')->where('uid',$v['id'])->delete();
			}
            return msg(1, '', '删除角色成功');

        }catch(PDOException $e){
            return msg(-1, '', $e->getMessage());
        }
    }

    // 获取所有的角色信息
    public function getRole()
    {
        return $this->select();
    }

	public function getRoleByCansee(){
		$roleId = DB::name('user')->where('id',session('id'))->value('role_id');
		$roleInfo = $this->where('id',$roleId)->find();
		if($roleInfo['can_see_type'] == 3){//所有
			return $this->select();
		}elseif($roleInfo['can_see_type'] == 2){//含子部门
			$departModel = new DepartmentModel();
			$departs = $departModel->getSonsByPid($roleInfo['department_id']);
			$departs[] = ['id'=>$roleInfo['department_id']];
			return $this->where(function($query)use($departs){
				foreach($departs as $v){
					$query->whereOr('department_id',$v['id']);
				}
			})->select();
		}elseif($roleInfo['can_see_type'] == 1){//仅本部门
			return $this->where('department_id',$roleInfo['department_id'])->select();
		}else{//仅自己
			return [0=>$roleInfo];
		}

	}

    // 获取角色的权限节点
    public function getRuleById($id)
    {
        $res = $this->field('rule')->where('id', $id)->find();
        return $res['rule'];
    }

    /**
     * 分配权限
     * @param $param
     */
    public function editAccess($param)
    {
        try{
            $this->save($param, ['id' => $param['id']]);
            return msg(1, '', '分配权限成功');

        }catch(PDOException $e){
            return msg(-1, '', $e->getMessage());
        }
    }

    /**
     * 获取角色信息
     * @param $id
     */
    public function getRoleInfo($id)
    {
        $result = $this->where('id', $id)->find()->toArray();
        // 超级管理员权限是 *
        if(empty($result['rule'])){
            $result['action'] = '';
            return $result;
        }else if('*' == $result['rule']){
            $where = '';
        }else{
            $where = 'id in(' . $result['rule'] . ')';
        }

        // 查询权限节点
        $nodeModel = new NodeModel();
        $res = $nodeModel->getActions($where);

        foreach($res as $key=>$vo){

            if('#' != $vo['action_name']){
                $result['action'][] = $vo['control_name'] . '/' . $vo['action_name'];
            }
        }

        return $result;
    }

    /**
     * [编辑角色可视权限]
     */
    public function editCansee($param){
        try{
            $this->save($param, ['id' => $param['id']]);
            return ['code'=>1,'msg'=>'设置成功'];
        }catch(PDOException $e){
            return ['code'=>0,'msg'=>'设置失败'.$e->getMessage()];
        }
    }

    /**
     * [通过部门ID获取该部门下的职员ID]
     */
    public function getUsersByDepartId($depart_id){
        $role_ids = $this->where('department_id',$depart_id)->field('id')->select();
		if(empty($role_ids)){
			$user_ids = [];
		}else{
			$user_ids = DB::name('user')->where(
	            function($query)use($role_ids){
	                foreach($role_ids as $v){
	                    $query->whereOr('role_id',$v['id']);
	                }
	            }
	        )->column('id');
		}
        return $user_ids;
    }
}
